package com.bm.console.business.impl;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

import com.bm.console.pojo.WebCountry;
import com.bm.console.pojo.mapper.WebCountryMapper;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.bm.console.business.ExchangeRateService;
import com.bm.console.business.WebCurrencyService;
import com.bm.console.pojo.WebCurrency;
import com.bm.console.pojo.WebExchangeRate;
import com.bm.console.pojo.mapper.WebCurrencyMapper;
import com.bm.console.pojo.mapper.WebExchangeRateMapper;
import com.sys.console.cookie.Authorized;
import com.sys.object.common.utils.DateUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Component
@Slf4j
public class ExchangeRateServiceImpl implements ExchangeRateService {

    @Autowired
    WebCurrencyMapper webCurrencyMapper;

    @Autowired
    WebExchangeRateMapper webExchangeRateMapper;

    @Autowired
    WebCountryMapper webCountryMapper;

    public static void main(String[] args) {
//		String path = "http://srh.bankofchina.com/search/whpj/search.jsp?pjname=1314";
//		try {
//			Document doc = Jsoup.connect(path).get();
//
//			Element table = doc.getElementsByClass("BOC_main").get(0);
//
//			Element tr = table.getElementsByTag("tr").get(1);
//
//			System.err.println(tr.toString());
//
//			String date = "2018.03.14 13:52:28";
//			date = date.replaceAll("\\.", "-");
//			System.err.println(date);
//
//			System.err.println(DateUtils.convertStr2Date_hh_mm_ss(date));
//
//		} catch (IOException e) {
//			e.printStackTrace();
//		}


        Calendar start = Calendar.getInstance();
        start.set(2018, 0, 1);
        Long startTIme = start.getTimeInMillis();

        Calendar end = Calendar.getInstance();
        end.set(2018, 3, 6);
        Long endTime = end.getTimeInMillis();

        Long oneDay = 1000 * 60 * 60 * 24l;

        Long time = startTIme;
        while (time <= endTime) {
            Date d = new Date(time);
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            System.out.println(df.format(d));
            time += oneDay;
        }
    }

    @Override
    public void saveCapture() {

        String path = "http://srh.bankofchina.com/search/whpj/search.jsp?pjname=";

        WebCurrency record = new WebCurrency();
        record.setCapture(true);
        record.setLimit(100);
        record.setOffset(0);
        ArrayList<WebCurrency> webCurrencys = webCurrencyMapper.selectByPage(record);
        for (WebCurrency webCurrency : webCurrencys) {
            Long CURRENCY_ID = webCurrency.getId();
            String name = webCurrency.getName();
            String urlRoot = path + CURRENCY_ID;

            log.info(urlRoot);
            try {
                Document doc = Jsoup.connect(urlRoot).get();

                Element table = doc.getElementsByClass("BOC_main").get(0);

                Element tr = table.getElementsByTag("tr").get(1);

                Elements tds = tr.getElementsByTag("td");


                if (!tds.isEmpty() && tds.size() == 7) {

                    String currency_name = tds.get(0).text().toString();
                    String buying_rate = tds.get(1).text().trim();
                    String cash_buying_rate = tds.get(2).text().trim(); // "现钞买入价";
                    String exch_bid = tds.get(3).text().trim();// "现汇卖出价";
                    String cash_bid = tds.get(4).text().trim();// "现钞卖出价";
                    //String safe_intermediate = tds.get(5).text().trim();// "外管局中间价";
                    String boe_conversion_rate = tds.get(5).text().trim();// "中行折算价";
                    // String exchange_rate = boe_conversion_rate / 100;// "汇率";
                    String release_time = tds.get(6).text().trim();// "发布时间";
                    release_time = release_time.replaceAll("\\.", "-");

                    WebExchangeRate entity = new WebExchangeRate();

                    entity.setCurrencyId(CURRENCY_ID);

                    entity.setCurrencyName(currency_name);

                    if (!StringUtils.isEmpty(buying_rate)) {
                        entity.setBuyingRate(Double.valueOf(buying_rate));
                    }

                    if (!StringUtils.isEmpty(cash_buying_rate)) {
                        entity.setCashBuyingRate(Double.valueOf(cash_buying_rate));
                    }

                    if (!StringUtils.isEmpty(exch_bid)) {
                        entity.setExchBid(Double.valueOf(exch_bid));
                    }

                    if (!StringUtils.isEmpty(cash_bid)) {
                        entity.setCashBid(Double.valueOf(cash_bid));
                    }

//                    if (!StringUtils.isEmpty(safe_intermediate)) {
//                        entity.setSafeIntermediate(Double.valueOf(safe_intermediate));
//                    }

                    if (!StringUtils.isEmpty(boe_conversion_rate)) {
                        entity.setBoeConversionRate(Double.valueOf(boe_conversion_rate));
                    }

                    if (!StringUtils.isEmpty(boe_conversion_rate)) {
                        Double exchange_rate = Double.valueOf(boe_conversion_rate) / 100;
                        entity.setExchangeRate(exchange_rate);
                    }
                    if (!StringUtils.isEmpty(release_time)) {
                        entity.setReleaseTime(DateUtils.convertStr2Date_hh_mm_ss(release_time));
                    }
                    entity.setCreateTime(new Date());

                    log.info(entity.toString());
                    webExchangeRateMapper.insert(entity);

                    //更新国家表的汇率
                    WebCountry country = new WebCountry();
                    country.setRate(Double.valueOf(boe_conversion_rate));
                    country.setCurrencyId(entity.getCurrencyId());
                    webCountryMapper.updateRateByCurrencyId(country);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    @Transactional(propagation= Propagation.NOT_SUPPORTED)
    public void saveCapture2() {

        String path = "http://srh.bankofchina.com/search/whpj/search.jsp?";
//        erectDate=2018-04-05
//        nothing=2018-04-06
//        pjname=1316
        WebCurrency record = new WebCurrency();
        record.setCapture(true);
        record.setLimit(100);
        record.setOffset(0);
        ArrayList<WebCurrency> webCurrencys = webCurrencyMapper.selectByPage(record);
        for (WebCurrency webCurrency : webCurrencys) {
            Long CURRENCY_ID = webCurrency.getId();
            String name = webCurrency.getName();
            String url = path + "pjname=" + CURRENCY_ID;


            Calendar start = Calendar.getInstance();
            start.set(2008, 0, 1);
            Long startTIme = start.getTimeInMillis();

            Calendar end = Calendar.getInstance();
            end.set(2018, 3, 6);
            Long endTime = end.getTimeInMillis();

            Long oneDay = 1000 * 60 * 60 * 24l;

            Long time = startTIme;
            while (time <= endTime) {
                Date d = new Date(time);
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                String date = df.format(d);
                System.out.println(date);
                time += oneDay;

                String url2 = url + "&erectDate=" + date + "&nothing=" + date;
                System.err.println(url2);
                try {
                    Document doc = Jsoup.connect(url2).get();
                    Element table = doc.getElementsByClass("BOC_main").get(0);
                    Element tr = table.getElementsByTag("tr").get(1);
                    System.err.println(tr.toString());
                    Elements tds = tr.getElementsByTag("td");
                    System.err.println(tds.size());
                    if (!tds.isEmpty() && tds.size() == 8) {
                        String currency_name = tds.get(0).text().toString();
                        String buying_rate = tds.get(1).text().trim();
                        String cash_buying_rate = tds.get(2).text().trim(); // "现钞买入价";
                        String exch_bid = tds.get(3).text().trim();// "现汇卖出价";
                        String cash_bid = tds.get(4).text().trim();// "现钞卖出价";
                        String safe_intermediate = tds.get(5).text().trim();// "外管局中间价";
                        String boe_conversion_rate = tds.get(6).text().trim();// "中行折算价";
                        //String exchange_rate = boe_conversion_rate / 100;// "汇率";
                        String release_time = tds.get(7).text().trim();// "发布时间";
                        release_time = release_time.replaceAll("\\.", "-");

                        WebExchangeRate entity = new WebExchangeRate();
                        entity.setCurrencyId(CURRENCY_ID);
                        entity.setCurrencyName(currency_name);
                        if (!StringUtils.isEmpty(buying_rate)) {
                            entity.setBuyingRate(Double.valueOf(buying_rate));
                        }
                        if (!StringUtils.isEmpty(cash_buying_rate)) {
                            entity.setCashBuyingRate(Double.valueOf(cash_buying_rate));
                        }
                        if (!StringUtils.isEmpty(exch_bid)) {
                            entity.setExchBid(Double.valueOf(exch_bid));
                        }
                        if (!StringUtils.isEmpty(cash_bid)) {
                            entity.setCashBid(Double.valueOf(cash_bid));
                        }
                        if (!StringUtils.isEmpty(safe_intermediate)) {
                            entity.setSafeIntermediate(Double.valueOf(safe_intermediate));
                        }
                        if (!StringUtils.isEmpty(boe_conversion_rate)) {
                            entity.setBoeConversionRate(Double.valueOf(boe_conversion_rate));
                        }
                        if (!StringUtils.isEmpty(boe_conversion_rate)) {
                            Double exchange_rate = Double.valueOf(boe_conversion_rate) / 100;
                            entity.setExchangeRate(exchange_rate);
                        }
                        if (!StringUtils.isEmpty(release_time)) {
                            entity.setReleaseTime(DateUtils.convertStr2Date_hh_mm_ss(release_time));
                        }
                        entity.setCreateTime(new Date());
                        System.err.println(entity.toString());
                        webExchangeRateMapper.insert(entity);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
